<template>
  <view class="rechargeMoney">
    <view class="title">充值金额</view>
    <view class="nums">
      <text v-for="item in numList" :key="item.id" @click="clickItem(item)"
        :class="id === item.id ? 'active' : ''">
        ￥{{ item.nums }}
      </text>
      <text @click="clickItem({ id: 3 })" :class="id === 3 ? 'active' : ''"
        v-if="id !== 3">其他金额</text>
      <view class="other" v-if="id === 3" @click="clickOther"> ￥{{ num }} </view>
    </view>

    <!-- <view class="paymentMethod">
      <text class="title">选择充值方式</text>
      <label v-for="item in paymentList" :key="item.id" class="item" @click="selectCheck(item)">
        <image :src="item.icon" mode="aspectFit"></image>
        <text>{{ item.name }}</text>
        <checkbox :checked="item.checked" class="checkbox" />
      </label>
    </view> -->
    <view class="paymentMethod">
      <text class="title">选择充值方式</text>
      <!-- #ifndef MP-TOUTIAO -->
      <text class="unable-pay" v-if="payStatus" @click="unableToPay()">无法支付？</text>
      <!-- #endif -->
      <label v-for="(item, index) in paymentList" :key="index" class="item"
        @click="selectCheck(item)">
        <image :src="item.icon" mode="aspectFit"></image>
        <text>{{ item.name }}</text>
        <checkbox :checked="item.checked" class="checkbox" />
      </label>
    </view>

    <view class="QrCode" v-if="qrCodeStatus" @click.stop="qrCodeStatus = false">
      <view class="QrCode_bg" @click.stop="clickQrCode_bg()">
        <image :src="QrCodeUrl"></image>
        <view class="text" @click.stop="preservation()">
          打开支付宝扫码支付
          <image :src="staticUrl() + '/carts/qrCodeDownload.png'"></image>
        </view>
      </view>
    </view>

    <input type="number" class="input" maxlength="8" :focus="focus" @input="getInput"
      v-if="id === 3" />
    <view class="btn">
      <view>充值: <text v-if="num">￥{{ num }}</text>
      </view>
      <view @click="pay">立即充值</view>
    </view>

    <!-- 无法支付弹窗 -->
    <view class="unable-pay-popup" v-if="isShowUnablePayPopup">
      <view class="overlay" @click="isShowUnablePayPopup = false"></view>
      <view class="content">
        <!-- 弹出层内容，可以根据需要自定义 -->
        <view class="titles"> 无法支付 ? </view>
        <view class="pay-method">
          <view class="pay-list">
            <view class="tips"> *部分手机无法支付，可选择此通道支付 </view>
            <view class="list" v-for="(item, index) in paymentMethod" :key="index"
              @click="selectCheckOrgin(item)">
              <view class="item">
                <image :src="item.icon" mode="aspectFit"></image>
                <text>{{ item.name }}</text>
                <checkbox :checked="item.checked" class="checkbox" />
              </view>
            </view>
          </view>
          <view class="btns" @click="pay"> 支付 </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  bindWechat,
  getWechatCode
} from '@/api/login/wechat.js'
import {
  wechatPayment,
  setUpBalanceOrder,
  polymerizationPay
} from '@/api/payment/index.js'
import wxQrcode from '@/utils/wxqrcode.js'
import {
  paySuitable,
  paySuitable1
} from '@/api/carts/index.js'
import {
  getAllRequest
} from '@/api/1.js'

export default {
  data () {
    return {
      num: '',
      id: '',
      focus: false,
      numList: [
        { id: 0, nums: '500' },
        { id: 1, nums: '800' },
        { id: 2, nums: '1000' }
      ],
      paymentList: [],
      paymentMethod: [],
      method: '',
      selectPayMethod: '',
      serviceType: '',
      paymentType: '',
      serviceType1: '',
      qrCodeStatus: false,
      QrCodeUrl: '',
      payStatus: false,
      isShowUnablePayPopup: false
    }
  },
  onShow () {
    this.paymentList = []
    paySuitable().then(res => {
      if (res.code === 200) {
        res.data.forEach(i => {
          this.$set(i, 'checked', false)
          if (i.method !== 'WALLET' && i.method !== 'BANK_TRANSFER') {
            this.paymentList.push(i)
          }
        })
        this.selectCheck(this.paymentList[0])
      }
    })
  },

  methods: {
    clickQrCode_bg () { },
    preservation () {
      let that = this
      uni.authorize({
        scope: 'scope.writePhotosAlbum',
        success () {
          that.saveAlbum()
        }
      })
    },
    saveAlbum () {
      uni.getSetting({
        //获取用户的当前设置
        success: res => {
          if (res.authSetting['scope.writePhotosAlbum']) {
            //验证用户是否授权可以访问相册
            this.saveImageToPhotosAlbum()
          } else {
            uni.authorize({
              //如果没有授权，向用户发起请求
              scope: 'scope.writePhotosAlbum',
              success: () => {
                this.saveImageToPhotosAlbum()
              },
              fail: () => {
                uni.showToast({
                  title: '请打开保存相册权限',
                  icon: 'none',
                  mask: true
                })
              }
            })
          }
        }
      })
    },
    saveImageToPhotosAlbum () {
      let base64 = this.QrCodeUrl.replace(/^data:image\/\w+;base64,/, '') //去掉data:image/png;base64,
      let filePath = wx.env.USER_DATA_PATH + '/hym_pay_qrcode.png'
      let that = this
      uni.getFileSystemManager().writeFile({
        filePath: filePath, //创建一个临时文件名
        data: base64, //写入的文本或二进制数据
        encoding: 'base64', //写入当前文件的字符编码
        success: res => {
          uni.saveImageToPhotosAlbum({
            filePath: filePath,
            success: function (res2) {
              uni.showToast({
                title: '保存成功',
                icon: 'none',
                mask: true
              })
            },
            fail: function (err) {
              uni.showToast({
                title: '保存失败',
                icon: 'none',
                mask: true
              })
            },
            complete: function () {
              that.qrCodeStatus = false
            }
          })
        }
      })
    },
    // 选中的支付方式
    selectCheck (val) {
      this.serviceType = val.serviceType || ''
      this.paymentType = val.paymentType || ''
      this.paymentList.forEach(i => {
        i.checked = false
      })
      this.method = val.method
      this.$nextTick(() => {
        val.checked = true
      })
    },
    // 无法支付 选中支付方式
    selectCheckOrgin (val) {
      this.serviceType1 = val.serviceType
      this.paymentMethod.forEach(i => {
        i.checked = false
      })
      this.selectPayMethod = val.method
      this.$nextTick(() => {
        val.checked = true
      })
    },
    clickOther () {
      this.focus = false
      setTimeout(() => {
        this.focus = true
      }, 200)
    },
    unableToPay () {
      this.paymentMethod = []
      paySuitable1()
        .then(res => {
          if (res.code === 200) {
            this.isShowUnablePayPopup = true
            if (res.code === 200) {
              res.data.forEach(i => {
                this.$set(i, 'checked', false)
                if (i.method !== 'WALLET' && i.method !== 'BANK_TRANSFER') {
                  this.paymentMethod.push(i)
                }
              })
              this.selectCheckOrgin(this.paymentMethod[0])
            }
          } else {
            uni.showToast({
              icon: 'none',
              title: '当前无法使用此支付渠道，请联系客服'
            })
          }
        })
        .catch(() => {
          uni.showToast({
            icon: 'none',
            title: '当前无法使用此支付渠道，请联系客服'
          })
        })
    },
    pay () {
      if (!this.num) {
        uni.showToast({ title: '请选择充值金额', icon: 'none', mask: true })
        return
      }
      setTimeout(() => { this.payStatus = true }, 3000)
      setUpBalanceOrder({ price: this.num }).then(r => {
        if (r.code === 200) {
          let cc = ''
          this.isShowUnablePayPopup ? (cc = this.selectPayMethod) : (cc = this.method)

          if (cc === 'DINPAY') {
            // if (this.serviceType === 'receipt_code_pay' || this.serviceType === 'alipay_app_pay') {
            if (this.paymentType === 'ALIPAY') {
              let clientType = ''
              // #ifdef MP
              clientType = 'NATIVE'
              // #endif
              // #ifndef MP
              clientType = 'APP'
              // #endif
              polymerizationPay('DINPAY', clientType, {
                sn: r.data.rechargeSn,
                // serviceType: this.serviceType,
                paymentType: this.paymentType,
                orderType: 'RECHARGE',
                appPay: true
              }).then(res => {
                if (res.code === 200) {
                  let prepay = res.data
                  // #ifdef MP
                  this.qrCodeStatus = true
                  this.QrCodeUrl = wxQrcode.createQrCodeImg(prepay)
                  // #endif
                  // #ifndef MP
                  plus.runtime.openURL(prepay)
                  // getAllRequest(prepay).then(r => {
                  // })
                  // const platform = uni.getSystemInfoSync().osName
                  // let alipayUri = ''
                  // if (platform === 'android') {
                  //   alipayUri =
                  //     'alipays://platformapi/startapp?appId=20000067&url=' +
                  //     JSON.parse(prepay).qrCode
                  // } else {
                  //   alipayUri =
                  //     'alipay://platformapi/startapp?appId=20000067&url=' +
                  //     JSON.parse(prepay).qrCode
                  // }
                  // plus.runtime.openURL(alipayUri)
                  // #endif
                }
              })
              return
            } else {
              // #ifdef MP-WEIXIN
              getWechatCode().then(code => {
                this.payWechat(code, r.data.rechargeSn)
              })
              // #endif
              // #ifndef MP-WEIXIN
              this.payWechat('', r.data.rechargeSn)
              // #endif
            }
            return
          }

          // let a = ""
          // this.isShowUnablePayPopup ? a = this.selectPayMethod : a = this.method

          // #ifdef MP-WEIXIN
          bindWechat().then(() => {
            getWechatCode().then(code => {
              wechatPayment(cc, 'RECHARGE', r.data.rechargeSn, code).then(
                response => {
                  if (response.code === 200) {
                    const weChatPayData = response.data
                    this.wechatPayment2(weChatPayData)
                  }
                })
            })
          })
          // #endif

          // #ifndef MP-WEIXIN
          wechatPayment(cc, 'RECHARGE', r.data.rechargeSn, '').then(response => {
            if (response.code === 200) {
              const weChatPayData = response.data
              if (cc === 'WECHAT') {
                this.wechatPayment2(weChatPayData, 'wxpay')
              }
              if (cc === 'ALIPAY') {
                this.wechatPayment2(weChatPayData, 'alipay')
              }
            }
          })
          // #endif
        }
      })
    },
    payWechat (codes, sn) {
      let clientType = ''
      // #ifdef MP-WEIXIN
      clientType = 'MP'
      // #endif
      // #ifndef MP-WEIXIN
      clientType = 'APP'
      // #endif
      // 微信
      polymerizationPay('DINPAY', clientType, {
        sn,
        // serviceType: this.serviceType,
        paymentType: this.paymentType,
        orderType: 'RECHARGE',
        code: codes
      }).then(res => {
        console.log(res)
        if (res.code === 200) {
          let prepay = res.data
          this.wechatPayment1(prepay)
        }
      })
    },
    // 聚合支付
    wechatPayment1 (param) {
      let prepay = ''
      // #ifdef MP-WEIXIN
      prepay = JSON.parse(param)
      uni.requestPayment({
        provider: 'wxpay', // 服务提提供商
        timeStamp: prepay.timeStamp, // 时间戳
        nonceStr: prepay.nonceStr, // 随机字符串
        package: prepay.package,
        signType: prepay.signType, // 签名算法
        paySign: prepay.paySign, // 签名
        success: function (res) {
          uni.navigateBack()
        },
        fail: function (err) {
          console.log('支付失败', err)
        }
      })
      // #endif
      // #ifndef MP-WEIXIN
      prepay = param
      plus.share.getServices(res => {
        let sweixin = null
        for (let i in res) {
          if (res[i].id === 'weixin') {
            sweixin = res[i]
          }
        }
        if (sweixin) {
          let a =
            `pages/pay_index/pay_index?appid=${prepay.appid}&oriaccid=${prepay.oriaccid}&apptype=${prepay.apptype}&prepayid=${prepay.prepayid}&sign=${prepay.sign}`
          sweixin.launchMiniProgram({ id: prepay.oriaccid, type: 0, path: a })
        } else {
          uni.showToast({
            icon: 'none',
            title: '未安装微信'
          })
        }
      })
      // #endif
    },

    wechatPayment2 (prepay, e) {
      // #ifdef MP-WEIXIN
      uni.requestPayment({
        provider: 'wxpay', // 服务提提供商
        timeStamp: prepay.timeStamp, // 时间戳
        nonceStr: prepay.nonceStr, // 随机字符串
        package: prepay.package, //
        signType: prepay.signType, // 签名算法
        paySign: prepay.paySign, // 签名
        success: function (res) {
          uni.navigateBack()
        },
        fail: function (err) {
          console.log('支付失败', err)
        }
      })
      // #endif
      // #ifndef MP-WEIXIN
      let orderInfo = ''
      if (e === 'alipay') {
        orderInfo = prepay
      }
      if (e === 'wxpay') {
        orderInfo = {
          package: prepay.package,
          appid: prepay.appid,
          sign: prepay.sign, // 签名
          signType: prepay.signType, // 签名算法
          partnerid: prepay.partnerid,
          prepayid: prepay.prepayid,
          noncestr: prepay.noncestr, // 随机字符串
          timestamp: prepay.timestamp // 时间戳
        }
      }
      uni.requestPayment({
        provider: e, // 服务提提供商
        orderInfo: orderInfo,
        success: function (res) {
          uni.navigateTo({
            url: '/subpackage/order/orderInfo?sn=' + that.sn
          })
        },
        fail: function (err) {
          console.log('支付失败', err)
        }
      })
      // #endif
    },

    getInput (e) {
      this.num = e.target.value
    },
    clickItem (val) {
      if (val.id === 3) {
        this.id = 3
        this.num = ''
        this.focus = true
      } else {
        this.num = val.nums
        this.id = val.id
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.rechargeMoney {
  width: 100%;
  max-height: 100vh;
  background: #fff;

  .title {
    font-size: 33rpx;
    margin: 85.14rpx 0 48.47rpx 30.56rpx;
  }

  .paymentMethod {
    background: #fff;
    margin: 0 25rpx;
    margin-top: 20rpx;
    padding-left: 22.22rpx;
    padding-bottom: 47.22rpx;

    .title {
      display: inline-block;
      font-size: 33rpx;
      font-weight: bold;
      margin: 56.25rpx 0 7rpx;
    }

    .unable-pay {
      width: 98rpx;
      height: 24rpx;
      font-size: 25rpx;
      color: #2871fc;
      margin-left: 10rpx;
    }

    .item {
      display: block;
      height: 50rpx;
      padding-top: 40.22rpx;

      image {
        width: 38.89rpx;
        height: 38.89rpx;
        vertical-align: sub;
        margin-right: 22.22rpx;
      }

      .checkbox {
        float: right;
      }
    }
  }

  .QrCode {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.3);
    z-index: 1;

    .QrCode_bg {
      width: 539rpx;
      height: 639rpx;
      background: #ffffff;
      border-radius: 17rpx;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);

      image {
        width: 387rpx;
        height: 387rpx;
        margin: 79.86rpx 76rpx 39.72rpx;
      }

      .text {
        height: 50rpx;
        line-height: 50rpx;
        font-size: 33rpx;
        font-weight: 500;
        color: #000000;
        text-align: center;

        image {
          width: 29.17rpx;
          height: 29.17rpx;
          margin: 0;
          margin-left: 16.67rpx;
          vertical-align: middle;
        }
      }
    }
  }

  .nums {
    padding: 0 27.78rpx;
    display: flex;
    flex-flow: row wrap;

    text {
      display: inline-block;
      width: 217rpx;
      height: 89rpx;
      line-height: 89rpx;
      text-align: center;
      font-size: 33rpx;
      background: #f9f9f9;
      border-radius: 11rpx;
      margin-bottom: 41.67rpx;
      margin-right: 22.22rpx;
    }

    text:nth-child(3) {
      margin-right: 0;
    }

    .active {
      color: #ef231b;
      background: #f8e3e2;
    }

    .other {
      box-sizing: border-box;
      min-width: 217rpx;
      height: 89rpx;
      line-height: 89rpx;
      font-size: 33rpx;
      color: #ef231b;
      background: #f8e3e2;
      border-radius: 11rpx;
      margin-bottom: 41.67rpx;
      display: flex;
      flex-flow: row nowrap;
      justify-content: space-around;

      text {
        width: 30rpx;
        background: none;
        margin: 0;
      }
    }
  }

  .input {
    color: transparent;
    transform: translateX(-1000%);
  }

  .btn {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 106rpx;
    display: flex;
    justify-content: space-between;
    background: #fff;

    view {
      font-size: 42rpx;
      margin-left: 50rpx;

      text {
        color: #ef231b;
      }
    }

    view:nth-child(2) {
      width: 200rpx;
      height: 56rpx;
      line-height: 56rpx;
      font-size: 29rpx;
      color: #fff;
      background: #2871fc;
      border-radius: 28rpx;
      text-align: center;
      margin-right: 50rpx;
    }
  }

  .unable-pay-popup {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;

    .overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      z-index: 999;
    }

    .content {
      position: relative;
      z-index: 1000;
      overflow: hidden;
      background: #f9f9f9;
      border-radius: 22rpx 22rpx 0rpx 0rpx;
      width: 100%;
      transition: bottom 0.3s ease-out;

      .titles {
        padding: 34rpx 0;
        width: 100%;
        text-align: center;
        font-size: 36rpx;
        font-weight: 600;
        color: #000000;
        background-color: #fff;
      }

      .pay-method {
        padding: 20rpx 26rpx;

        .pay-list {
          background: #ffffff;
          border-radius: 22rpx;
          padding: 50rpx 0 0 22rpx;
          margin-bottom: 180rpx;

          .tips {
            width: 508rpx;
            height: 28rpx;
            font-size: 29rpx;
            color: #ef231b;
            margin-bottom: 45rpx;
          }

          // .list {
          // 	margin-bottom: 46rpx;
          // }

          .item {
            display: block;
            height: 50rpx;
            padding-bottom: 46rpx;

            image {
              width: 38rpx;
              height: 38rpx;
              vertical-align: sub;
              margin-right: 22rpx;
            }

            .checkbox {
              float: right;
            }
          }
        }
      }

      .btns {
        width: 678rpx;
        height: 80rpx;
        background: #2871fc;
        border-radius: 39rpx;
        text-align: center;
        font-size: 29rpx;
        color: #ffffff;
        line-height: 80rpx;
        margin: 0 auto;
      }
    }
  }
}
</style>